import axios from './factory';
// import router from '@/router/index'
import Vue from "vue";
//引入增强js
import '../../util/extends/toFirstUpperCase';
import router from 'router';
import * as Login from "@/service/login";

//没有api的配置链接加上static,自动分类
//这叫api树

class ApiConfig {
    constructor() {
        this.api = {}
        this.api.admin={
            login:{server:'/api/admin/login',mock:''},//登录
            logout:{server:'/api/admin/logout',mock:''},//登出
            admin:{server:'/api/admin',mock:''},//管理员列表
            adminRoles:{server:'/api/admin/menu'},//权限菜单
            adminLog:{server:'/api/admin-operation-log',mock:''},//管理员操作日志
        }
        this.api.drive={
            getDriveList:{server:'/api/btm',mock:''},//获取设备列表
            btmLog:{server:'/api/btm-operation-log',mock:''},//获取操作日志
            systemLog:{server:'/api/btm-system-log',mock:''},//获取系统日志
            alarmLog:{server:'/api/btm/alarm',mock:''},//获取警告列表
            countryAmount:{server:'/api/btm/country-amount',mock:''},//国家金额汇总
            exportLog:{server:'/api/btm-operation-log/export',mock:''},//btm导出日志
        }
        this.api.country={
            getCountry:{server:'/api/country',mock:''}//获取国家列表
        }
        this.api.user={
            getUser:{server:'/api/user',mock:''}//获取用户列表
        }
        this.api.userVerification={//用户认证接口
            apply:{server:'/api/user-verification/apply',mock:''},//用户身份认证申请列表
        }
        this.api.account={
            accountTotal:{server:'/api/account/virtual-currency/summary',mock:''},//虚拟币金额汇总
            virtualCurrency:{server:'/api/account/virtual-currency/count',mock:''},//用户虚拟币总数
            platform:{server:'/api/account/virtual-currency/platform',mock:''},//平台虚拟币总数
            userTop:{server:'/api/account/virtual-currency/user/top',mock:''},//用户排行
        }
        this.api.accountTransaction={
            accountTransaction:{server:'/api/account-transaction',mock:''}//交易日志
        }
        this.api.exchange={
            exchange:{server:'/api/exchange-rate',mock:''}//汇率换算
        }
        this.api.notice={
            noticeList:{server:'/api/notice',mock:''},//公告列表
        }
        this.api.advert={
            advertList:{server:'/api/advert',mock:''},//广告投放
        }
        this.api.file={
            fileImg:{server:'/api/file/enc',mock:''}//上传图片
        }
        this.api.setting={
            setting:{server:'/api/setting/system',mock:''}//获取设置信息
        }
        this.api.messageTemplate={
            messageTemplateList:{server:'/api/message-template',mock:''}//消息推送列表
        }
        this.api.settingBtn={
            settingBtnList:{server:'/api/setting/btm',mock:''}//获取btm设置列表
        }
    }


    /**
     * 格式化api链接
     * @Author BillionChen
     * @param  {Boolean}   isToMock [是否转为mock链接/若为false则会判断当前是否使用mock数据]
     * @param  {Boolean}   isStatic [是否静态api(没有ajax方法的配置链接)]
     * @return {[type]}             [description]
     */
    toUrl(isToMock = false, isStatic = undefined) {
        let rs = {};
        for (let v in this.api) {
            rs[v] = {};
            for (let item in this.api[v]) {
                if (this.api[v][item].static !== isStatic) continue; //静态链接不纳入api
                // if (isToMock || process.env.MOCK_ON === 'mock' ) {
                //     this.api[v][item]["mock"]
                //         ? rs[v][item] = this.api[v][item]["mock"]
                //         : console.log(`mock url lost: api.${v}.${item}`)
                // }
                if(item === 'authorization'){
                    this.api[v][item]["mock"]
                        ? rs[v][item] = this.api[v][item]["mock"]
                        : console.log(`mock url lost: api.${v}.${item}`)
                }else{
                    this.api[v][item]["server"]
                        ? rs[v][item] = process.env.BASE_URL + this.api[v][item]["server"]
                        : console.log(`server url lost: api.${v}.${item}`)
                }
            }
        }
        return rs;
    }

    toApi(request = 'post') {
        let urlConfigs = this.toUrl();
        let rs = {};
            for (let module in urlConfigs) {
                rs[module] = {};

                if(request === 'get'){
                    for (let item in urlConfigs[module]) {
                        rs[module][item] = (params = {},flag,stringUrl,headersStr = 'application/x-www-form-urlencoded; charset=utf-8') => {
                            
                            if(!flag){return axios.get(urlConfigs[module][item], {params},{
                                headers: {
                                    'Content-Type': headersStr,
                                },
                            })
                                .then(this.checkStatus)
                                .then(this.checkJson)
                                .then(this.checkError)
                        }else{
                            return axios.get(urlConfigs[module][item]+'/'+stringUrl, {params},{
                                headers: {
                                    'Content-Type': headersStr,
                                },
                            })
                                .then(this.checkStatus)
                                .then(this.checkJson)
                                .then(this.checkError)
                        }
                        }
                    }
                }

                if(request === 'put'){
                    for (let item in urlConfigs[module]) {
                        rs[module][item] = (id,params = {},headersStr = 'application/json; charset=utf-8') => {
                            return axios.put(urlConfigs[module][item]+(id?('/'+id):""), params,{
                                headers: {
                                    'Content-Type': headersStr,
                                },
                            })
                                .then(this.checkStatus)
                                .then(this.checkJson)
                                .then(this.checkError)
                        }
                    }
                }
                if(request=== 'patch'){
                    for (let item in urlConfigs[module]) {
                        rs[module][item] = (id,params = {},headersStr = 'application/json; charset=utf-8') => {
                            return axios.patch(urlConfigs[module][item]+(id?('/'+id):""), params,{
                                headers: {
                                    'Content-Type': headersStr,
                                },
                            })
                                .then(this.checkStatus)
                                .then(this.checkJson)
                                .then(this.checkError)
                        }
                    }
                }
                if(request=== 'delete'){
                    for (let item in urlConfigs[module]) {
                        rs[module][item] = (id,params = {},headersStr = 'application/json; charset=utf-8') => {
                            return axios.delete(urlConfigs[module][item]+(id?('/'+id):""), params,{
                                headers: {
                                    'Content-Type': headersStr,
                                },
                            })
                                .then(this.checkStatus)
                                .then(this.checkJson)
                                .then(this.checkError)
                        }
                    }
                }

                if(request === 'post'){
                    for (let item in urlConfigs[module]) {
                        rs[module][item] = (params = {},headersStr = 'application/json; charset=utf-8') => {
                            return axios.post(urlConfigs[module][item], params,{
                                headers: {
                                    'Content-Type': headersStr,
                                },
                            })
                                .then(this.checkStatus)
                                .then(this.checkJson)
                                .then(this.checkError)
                        }
                    }
                }
            // }
        }
        return rs;
    }

    checkStatus(response) {
        // //console.log(response)
        // debugger
        // 如果 http 状态码正常, 则直接返回数据
        // 异常状态下, 把错误信息返回去
        // 因为前面我们把错误扶正了, 不然像 404, 500 这样的错误是走不到这里的
        if (!response) {
            return {
                status: false,
                code: null,
                exception: "no response!please logout!",
                // login: false,
            }//未登录被302拦截后,没有返回//这里应该有坑的...但暂时是不会出问题的
        }
        // if (response.status == 400) {
        //     return {
        //         status: false,
        //         data: null,
        //         message:response.message
        //     };
        // }
        // if(response.status==409){
        //     return{
        //         status:false,
        //         data:response.data,
        //         message:response.data.message
        //     }
        // }
        return [200, 304].indexOf(response.status) !== -1 ? response.data : {
            status: false,
            code: response.status,
            // msg: response.statusText,
            exception: [response.status, response.statusText, response.request.responseURL].join(" "),
            // data: response.statusText,
            message:response.data.message,
        }
    }

    checkJson(data) {
        return (typeof data).toLowerCase() === 'string'
            ? JSON.parse(data)
            : data
    }

    checkError(data) {
        // //console.log(data);
        // //console.log(data);
        if(data && data.status){
            return data;
        }else{
            //console.log(data)
            let elLoadingMask = document.querySelector('.el-loading-mask.is-fullscreen');
            if(elLoadingMask){
                elLoadingMask.style.display = "none";
            }
            let codeArr  = ['501','500','ECO001','ECO003','ECO004','ECO005','ECO006','ECO007','ECO008','ECO009','ECO100','ECO101','ECO102','ECO103','ECO999'];
            if(codeArr.join(',').indexOf(data.code) !== -1){
                let msg = data.message || data.msg || data.exception || data.errMsg;
                // new Vue().$message.warning(msg);
                new Vue().$notify.error({
                    title: '错误',
                    message: msg
                });
                return data;
            }
            if(data.code == '500'||data.code=='404'){
                let msg = data.message || data.msg || data.exception || data.errMsg;
                new Vue().$notify.error({title:'错误',message:msg});
            }
            // 401 token过期
            if(data.code=='401'){
                let msg = data.message || data.msg || data.exception || data.errMsg;
                new Vue().$notify.error({title:'错误',message:msg});
                // console.log(router);
                setTimeout(()=>{
                    Login.clearLogin();
                    router.push(Login.getLoginPath());
                },1000);
            }
            if(data.code== 400){
                //console.log(data);
                new Vue().$notify.error({title:'错误',message:data.message});
                data.status==false;
                return data;
            }
            if(data.data&&data.data.code=='409'){
                // alert('')
                //console.log(data);
                new Vue().$notify.error({title:'错误',message:data.message});
                data.status==false;
                return data;
                // Login.clearLogin();
                // this.$router.push(Login.getLoginPath());
            }
            if(data.code==403){
                new Vue().$notify.error({title:'错误',message:data.message});
                data.status==false;
                return data;
            }
        }
        if(data&&!data.status){
            return data;
        }
    }

  // getToken(){
  //   axios
  //     .get("http://mtdsuat.oppein.com:1120/login/token/get?orgNo=OPPEIN.COM&account=op.36964&password=111111&systemVersion=&baseDataVersion=&clientId=&device=")
  //     .then(function(response) {
  //       let token = response.data.token;
  //       // //console.log( JSON.parse(response.data));
  //       if (token) {
  //         window.localStorage.setItem("token", token);
  //       } else {
  //         token = JSON.parse(response.data).data.token;
  //       }
  //       window.localStorage.setItem("token", token);
  //     })
  //     .catch(function(error) {
  //       //console.log("token获取失败");
  //     });
  // }
}

export const staticApi = new ApiConfig().toUrl(false, true);
export const getUrl = new ApiConfig().toUrl();
export const mock = new ApiConfig().toUrl(true);
export const apiGet = new ApiConfig().toApi('get');
export const apiPut = new ApiConfig().toApi('put');
export const api = new ApiConfig().toApi('post');
export const apiPatch = new ApiConfig().toApi('patch');
export const apiDelete = new ApiConfig().toApi('delete');
